package servers

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"path/filepath"
	"strings"
	"vala/configs"
	"vala/repositorys"
	"vala/services"
	"vala/sites"
	"vala/tools"
)

// 获取战点管理
func GetSiteManager() sites.SiteManager {
	return sites.NewSiteManager(filepath.Join(tools.GetBasePath(), "nginx", "conf", configs.CONFIG_DIR))
}

type Server struct {
	Host string
	Port string
}

// 运行Http Server
func (server Server) Run() {
	error := http.ListenAndServe(server.Host+":"+server.Port, nil)
	if error != nil {
		log.Fatal("Error:", error)
	}
}

// 处理内容
func (server Server) Handle() {
	fmt.Println(filepath.Join(tools.GetAdminPath(), "static"))
	http.Handle("/static/", http.FileServer(http.Dir(tools.GetAdminPath())))
	// MANAGER
	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		// 异常捕获
		defer func() {
			if r := recover(); r != nil {
				tools.ResponseError(writer, r)
			}
		}()

		content, error := ioutil.ReadFile(filepath.Join(tools.GetAdminPath(), "index.html"))
		if error != nil {
			panic(error)
		}
		writer.Header().Set("Content-Type", "text/html;charset=utf-8")
		writer.Write(content)
	})
	//
	serviceManager := services.NewServiceManager()
	// SERVICES
	http.HandleFunc("/services", func(writer http.ResponseWriter, request *http.Request) {
		tools.Cors(writer)

		// 异常捕获
		defer func() {
			if r := recover(); r != nil {
				tools.ResponseError(writer, r)
			}
		}()

		log.Printf("Request: Method %s \n", request.Method)
		action := request.FormValue("action")
		service := request.FormValue("service")

		log.Printf("Request: Action %s \n", action)
		switch action {
		case "ls":
			fmt.Println(serviceManager.GetAll())
			var serviceInfos []services.ServiceInfo
			for _, serviceDefine := range serviceManager.GetAll() {
				serviceInfos = append(serviceInfos, services.ServiceInfo{
					Name:   serviceDefine.Name,
					Flag:   strings.ToLower(serviceDefine.Name),
					Status: serviceDefine.Instance().Status(),
				})
			}
			fmt.Println(serviceInfos)
			output, _ := json.Marshal(serviceInfos)
			writer.Write(output)
			writer.WriteHeader(http.StatusOK)
		case "start":
			service,error := serviceManager.GetService(service)
			if error != nil {
				panic(error)
			}
			service.Start()
			log.Printf("Request: Start %s \n", service)
			tools.ResponseOk(writer)
		case "stop":
			service,error := serviceManager.GetService(service)
			if error != nil {
				panic(error)
			}
			service.Stop()
			log.Printf("Request: Stop %s \n", service)
			tools.ResponseOk(writer)
		case "reload":
			service,error := serviceManager.GetService(service)
			if error != nil {
				panic(error)
			}
			service.Reload()
			log.Printf("Request: Reload %s \n", service)
			tools.ResponseOk(writer)
		}
	})
	// SITES
	http.HandleFunc("/sites", func(writer http.ResponseWriter, request *http.Request) {

		// 异常捕获
		defer func() {
			if r := recover(); r != nil {
				tools.ResponseError(writer, r)
			}
		}()

		tools.Cors(writer)
		action := request.FormValue("action")
		byt, _ := ioutil.ReadAll(request.Body)
		fmt.Println(string(byt))
		switch action {
		case "ls":
			output, _ := json.Marshal(GetSiteManager().List())
			writer.Write(output)
			writer.WriteHeader(http.StatusOK)
		case "create":
			if !GetSiteManager().Exists(repositorys.Site{Name: request.FormValue("name")}) {
				// 验证参数
				if request.FormValue("name") == "" {
					panic(errors.New("Name Must Right Value"))
				}
				if request.FormValue("path") == "" {
					panic(errors.New("Path Must Right Value"))
				}

				// 创建站点
				GetSiteManager().Add(repositorys.Site{
					Name:     request.FormValue("name"),
					Path:     request.FormValue("path"),
					Template: ConsTemplate(request),
				})
			}
			tools.ResponseOk(writer)
		case "delete":
			GetSiteManager().Delete(repositorys.Site{
				Name: request.FormValue("name"),
			})
			tools.ResponseOk(writer)
		case "update":
			// 验证参数
			if request.FormValue("name") == "" {
				panic(errors.New("Name Must Right Value"))
			}
			if request.FormValue("path") == "" {
				panic(errors.New("Path Must Right Value"))
			}

			GetSiteManager().Update(repositorys.Site{
				Name:     request.FormValue("name"),
				Path:     request.FormValue("path"),
				Template: ConsTemplate(request),
			})
			tools.ResponseOk(writer)
		}
	})
}

func ConsTemplate(request *http.Request) repositorys.Template {
	var template repositorys.Template

	var templateFlag = request.FormValue("template")
	switch templateFlag {
	case "Laravel":
		template = repositorys.Template{
			Name:       templateFlag,
			ServerName: request.FormValue("serverName"),
			ServerPath: filepath.Join(request.FormValue("path"), "public"),
		}
	case "ThinkPHP5":
		template = repositorys.Template{
			Name:       templateFlag,
			ServerName: request.FormValue("serverName"),
			ServerPath: filepath.Join(request.FormValue("path"), "public"),
		}
	default:
		template = repositorys.Template{
			Name:       "Custom",
			ServerName: request.FormValue("name"),
			ServerPath: request.FormValue("path"),
		}
	}
	// 验证
	if template.ServerName == "" {
		panic(errors.New("Server Name Must Right Value"))
	}

	return template
}

func (server Server) Release() {

}
